package com.coding.base.util;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;
import sun.misc.BASE64Decoder;

import javax.sql.rowset.serial.SerialBlob;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@SuppressWarnings("restriction")
public class OSSManageUtil {
    /**
     * 上传OSS服务器文件 @Title: uploadFile
     * <p>
     * remotePath @param oss服务器二级目录
     *
     * @throws Exception 设定文件 @return String
     *                   返回类型 @throws
     */
    @SuppressWarnings("deprecation")
    public static String uploadFile(InputStream fileContent, String remotePath, String fileName) throws Exception {
        //随机名处理
        fileName = "yw_" + fileName.substring(fileName.lastIndexOf("."));
        // 加载配置文件，初始化OSSClient
        OSSConfigure ossConfigure = new OSSConfigure("oss.properties");
        OSSClient ossClient = new OSSClient(ossConfigure.getEndpoint(), ossConfigure.getAccessKeyId(),
                ossConfigure.getAccessKeySecret());
        // 定义二级目录
        String remoteFilePath = remotePath.substring(0, remotePath.length()).replaceAll("\\\\", "/") + "/";
        // 创建上传Object的Metadata
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentLength(fileContent.available());
        objectMetadata.setContentEncoding("utf-8");
        objectMetadata.setCacheControl("no-cache");
        objectMetadata.setHeader("Pragma", "no-cache");
        objectMetadata.setContentType(contentType(fileName.substring(fileName.lastIndexOf("."))));
        objectMetadata.setContentDisposition("inline;filename=" + fileName);
        // 上传文件
        ossClient.putObject(ossConfigure.getBucketName(), remoteFilePath + fileName, fileContent, objectMetadata);
        // 关闭OSSClient
        ossClient.shutdown();
        // 关闭io流
        fileContent.close();
        return ossConfigure.getAccessUrl() + "/" + remoteFilePath + fileName;
    }

    // 下载文件
    @SuppressWarnings({"unused", "deprecation"})
    public static void downloadFile(OSSConfigure ossConfigure, String key, String filename)
            throws Exception, IOException {
        // 初始化OSSClient
        OSSClient ossClient = new OSSClient(ossConfigure.getEndpoint(), ossConfigure.getAccessKeyId(),
                ossConfigure.getAccessKeySecret());
        OSSObject object = ossClient.getObject(ossConfigure.getBucketName(), key);
        // 获取ObjectMeta
        ObjectMetadata meta = object.getObjectMetadata();

        // 获取Object的输入流
        InputStream objectContent = object.getObjectContent();

        ObjectMetadata objectData = ossClient.getObject(new GetObjectRequest(ossConfigure.getBucketName(), key),
                new File(filename));
        // 关闭数据流
        objectContent.close();

    }

    /**
     * 根据key删除OSS服务器上的文件 @Title: deleteFile @Description: @param @param
     * ossConfigure @param @param filePath 设定文件 @return void 返回类型 @throws
     *
     * @throws IOException
     */
    @SuppressWarnings("deprecation")
    public static void deleteFile(String filePath) throws IOException {
        // 加载配置文件，初始化OSSClient
        OSSConfigure ossConfigure = new OSSConfigure("/oss.properties");
        OSSClient ossClient = new OSSClient(ossConfigure.getEndpoint(), ossConfigure.getAccessKeyId(),
                ossConfigure.getAccessKeySecret());
        ossClient.deleteObject(getOSSBucketName(filePath), getOSSFileName(filePath));
    }

    /**
     * Description: 判断OSS服务文件上传时文件的contentType @Version1.0
     *
     * @param FilenameExtension 文件后缀
     * @return String
     */
    public static String contentType(String FilenameExtension) {
        if (FilenameExtension.equals(".BMP") || FilenameExtension.equals(".bmp")) {
            return "image/bmp";
        }
        if (FilenameExtension.equals(".GIF") || FilenameExtension.equals(".gif")) {
            return "image/gif";
        }
        if (FilenameExtension.equals(".JPEG") || FilenameExtension.equals(".jpeg") || FilenameExtension.equals(".JPG")
                || FilenameExtension.equals(".jpg") || FilenameExtension.equals(".PNG")
                || FilenameExtension.equals(".png")) {
            return "image/jpeg";
        }
        if (FilenameExtension.equals(".HTML") || FilenameExtension.equals(".html")) {
            return "text/html";
        }
        if (FilenameExtension.equals(".TXT") || FilenameExtension.equals(".txt")) {
            return "text/plain";
        }
        if (FilenameExtension.equals(".VSD") || FilenameExtension.equals(".vsd")) {
            return "application/vnd.visio";
        }
        if (FilenameExtension.equals(".PPTX") || FilenameExtension.equals(".pptx") || FilenameExtension.equals(".PPT")
                || FilenameExtension.equals(".ppt")) {
            return "application/vnd.ms-powerpoint";
        }
        if (FilenameExtension.equals(".DOCX") || FilenameExtension.equals(".docx") || FilenameExtension.equals(".DOC")
                || FilenameExtension.equals(".doc")) {
            return "application/msword";
        }
        if (FilenameExtension.equals(".XML") || FilenameExtension.equals(".xml")) {
            return "text/xml";
        }
        if (FilenameExtension.equals(".apk") || FilenameExtension.equals(".APK")) {
            return "application/octet-stream";
        }
        return "text/html";
    }

    @SuppressWarnings("unused")
    public static void main(String[] args) {
        try {
            OSSConfigure ossConfigure = new OSSConfigure("oss.properties");
            //deleteFile("http://ceshi1111111.oss-cn-hangzhou.aliyuncs.com/cardImage/yw_1524552090254.png");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }


    /**
     * @param fileUrl 文件url
     * @return String bucketName
     * @MethodName: getOSSBucketName
     * @Description: 根据url获取bucketName
     */
    private static String getOSSBucketName(String fileUrl) {
        String http = "http://";
        String https = "https://";
        int httpIndex = fileUrl.indexOf(http);
        int httpsIndex = fileUrl.indexOf(https);
        int startIndex = 0;
        if (httpIndex == -1) {
            if (httpsIndex == -1) {
                return null;
            } else {
                startIndex = httpsIndex + https.length();
            }
        } else {
            startIndex = httpIndex + http.length();
        }
        int endIndex = fileUrl.indexOf(".oss-");
        return fileUrl.substring(startIndex, endIndex);
    }

    /**
     * @param fileUrl 文件url
     * @return String fileName
     * @MethodName: getFileName
     * @Description: 根据url获取fileName
     */
    private static String getOSSFileName(String fileUrl) {
        String str = "aliyuncs.com/";
        int beginIndex = fileUrl.indexOf(str);
        if (beginIndex == -1) {
            return null;
        }
        return fileUrl.substring(beginIndex + str.length());
    }

    /**
     * @return List<String>  fileName集合
     * @MethodName: getFileName
     * @Description: 根据url获取fileNames集合
     */
    @SuppressWarnings("unused")
    private static List<String> getOSSFileName(List<String> fileUrls) {
        List<String> names = new ArrayList<>();
        for (String url : fileUrls) {
            names.add(getOSSFileName(url));
        }
        return names;
    }

    public static String testAddUploadFileInfo(String base64Img, String remotePath, String fileName) {
        try {
            SerialBlob serialBlob = decodeToImage(base64Img);
            InputStream binaryStream = serialBlob.getBinaryStream();
            String url = OSSManageUtil.uploadFile(binaryStream, remotePath, fileName);
            System.out.println(url);
            return url;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    private static SerialBlob decodeToImage(String imageString) throws Exception {
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] imageByte = decoder.decodeBuffer(imageString);
        return new SerialBlob(imageByte);
    }
}